/* eslint-disable no-use-before-define */
/* eslint-disable react/no-unstable-nested-components */
import React, { useMemo, useState } from 'react';
import { ArrowDownOutlined } from '@ant-design/icons';
import { Button, Popconfirm, Radio, Table, Form, Input, Modal } from 'antd';
import { PageType, RewardColumns } from '../constant';
import Styles from './index.less';

interface RewardType {
  pageType: string;
  channelCodeList: any[];
  setChannelCodeList: (arr: any[]) => void;
  offsetList: any[];
  setOffsetList: (arr: any[]) => void;
  detailRecord: Record<string, string>;
}

// eslint-disable-next-line react/function-component-definition
const EditableCell: React.FC<any> = ({
  editing,
  dataIndex,
  title,
  record,
  index,
  children,
  ...restProps
}) => (
  <td {...restProps}>
    {editing ? (
      <div className={Styles.inputBox}>
        <div>
          <Form.Item name={`${dataIndex}-d`} style={{ margin: 0 }}>
            <Input placeholder="请输入" />
          </Form.Item>
        </div>
        <div>
          <Form.Item name={`${dataIndex}-e`} style={{ margin: 0 }}>
            <Input placeholder="请输入" />
          </Form.Item>
        </div>{' '}
        <div>
          <Form.Item name={`${dataIndex}-f`} style={{ margin: 0 }}>
            <Input placeholder="请输入" />
          </Form.Item>
        </div>
      </div>
    ) : (
      children
    )}
  </td>
);

export function Reward({
  pageType,
  channelCodeList,
  setChannelCodeList,
  offsetList,
  setOffsetList,
  detailRecord,
}: RewardType) {
  const [editingKey, setEditingKey] = useState('');
  const [form] = Form.useForm();
  const [ladderColCount, setLadderColCount] = useState(1);
  const [offsetCount, setOffset] = useState(1);
  const [tabValue, setTabValue] = useState('1');
  const [mode, setMode] = useState(1);
  const [visible, setVisible] = useState(false);
  const [rewardList, setRewardList] = useState<any[]>([
    { id: '1' },
    { id: '2' },
  ]);
  const [selectRows, setSelectRows] = useState<any[]>([]);

  const onDelete = (id: string) => {
    const index = channelCodeList.findIndex((item) => id === item.key);
    channelCodeList.splice(index, 1);
    setChannelCodeList([...channelCodeList]);
  };

  const add = () => {
    setVisible(true);
    // form.resetFields();
    // const obj = { key: '' };
    // obj.key = (Math.floor(Math.random() * (100000000 - 1)) + 1).toString();
    // setChannelCodeList([obj, ...channelCodeList]);
    // setEditingKey(obj.key);
  };

  // 阶梯编辑,和冲单阶梯编辑
  const edit = (record: Record<string, any>) => {
    const arr = Object.keys(record).filter((key) => key.includes('jieti'));
    const obj: any = {
      e: record.e,
      f: record.f,
    };
    arr.forEach((key) => {
      for (const k in record[key]) {
        obj[`${key}-${k}`] = record[key][k];
      }
    });
    form.resetFields();
    form.setFieldsValue(obj);
    setEditingKey(record.key);
  };

  // 阶梯保存,和冲单阶梯保存
  const onSave = async (
    dataList: any[],
    setData: (list: any[]) => void,
    count: number,
  ) => {
    const data = await form.validateFields();
    const arr = Object.keys(data).filter((key) => key.includes('jieti'));

    // eslint-disable-next-line no-plusplus
    for (let i = 1; i <= count; i++) {
      const keys = arr.filter((key) => key.split('-')[0] === `jieti${i || ''}`);
      keys.forEach((key) => {
        const jieti = key.split('-')[0];
        const field = key.split('-')[1];
        data[jieti] = data[jieti] || {};
        data[jieti][field] = data[key];
      });
    }

    const index = dataList.findIndex((item) => item.key === editingKey);
    // eslint-disable-next-line no-param-reassign
    dataList[index] = {
      ...dataList[index],
      ...data,
      key: editingKey,
    };
    setData([...dataList]);
    setEditingKey('');
  };

  // 添加阶梯
  const onAddLadderCol = () => {
    setLadderColCount(ladderColCount + 1);
  };

  // 添加冲单阶梯
  const onAddOffsetCol = () => {
    setOffset(offsetCount + 1);
  };

  // 阶梯列
  const ladderCol = useMemo(
    () => (index: number) => {
      const key = `jieti${index || ''}`;
      return {
        title: () => (
          <div className={Styles.thBox}>
            {index === ladderColCount && pageType !== PageType.Detail && (
              <span
                className={Styles.add}
                aria-hidden
                onClick={() => onAddLadderCol()}
              >
                +
              </span>
            )}
            <div className={Styles.title}>阶梯{index}</div>
            <div className={Styles.item}>
              <span>阶梯上限数量</span>
              <span>奖励金额/单</span>
              <span>BD跟单费</span>
            </div>
          </div>
        ),
        dataIndex: key,
        align: 'center',
        width: 300,
        render: (filed: string, record: Record<string, any>) => (
          <div className={Styles.tdBox}>
            <span>{record[key] && record[key].d}</span>
            <span>{record[key] && record[key].e}</span>
            <span>{record[key] && record[key].f}</span>
          </div>
        ),
        editable: true,
      };
    },
    [ladderColCount, channelCodeList],
  );

  // 冲单列
  const offsetCol = useMemo(
    () => (index: number) => {
      const key = `jieti${index || ''}`;
      return {
        title: () => (
          <div className={Styles.thBox}>
            {index === offsetCount && pageType !== PageType.Detail && (
              <span
                className={Styles.add}
                aria-hidden
                onClick={() => onAddOffsetCol()}
              >
                +
              </span>
            )}
            <div className={Styles.title}>冲单阶梯{index}</div>
            <div className={Styles.item}>
              <span>阶梯上限数量</span>
              <span>奖励金额/单</span>
              <span>BD跟单费</span>
            </div>
          </div>
        ),
        dataIndex: key,
        align: 'center',
        width: 300,
        render: (filed: string, record: Record<string, any>) => (
          <div className={Styles.tdBox}>
            <span>{record[key] && record[key].d}</span>
            <span>{record[key] && record[key].e}</span>
            <span>{record[key] && record[key].f}</span>
          </div>
        ),
        editable: true,
      };
    },
    [offsetCount, channelCodeList],
  );

  const Colnums: any[] = useMemo(() => {
    const arr: any[] = [...RewardColumns];

    if (tabValue === '1') {
      // eslint-disable-next-line no-plusplus
      for (let i = 1; i <= ladderColCount; i++) {
        arr.push({ ...ladderCol(i) });
      }
    } else {
      // eslint-disable-next-line no-plusplus
      for (let i = 1; i <= offsetCount; i++) {
        arr.push({ ...offsetCol(i) });
      }
    }

    if (pageType !== PageType.Detail) {
      if (arr.find((item) => item.dataIndex === 'op')) return arr;
      arr.push({
        title: '操作',
        dataIndex: 'op',
        align: 'center',
        width: 100,
        fixed: 'right',
        render: (key: string, record: Record<string, string>) => (
          <div className={Styles.operationBtn}>
            {editingKey === record.key ? (
              <>
                <span
                  onClick={() =>
                    tabValue === '1'
                      ? onSave(
                          channelCodeList,
                          setChannelCodeList,
                          ladderColCount,
                        )
                      : onSave(offsetList, setOffsetList, offsetCount)
                  }
                  aria-hidden
                >
                  保存
                </span>
                <span onClick={() => setEditingKey('')} aria-hidden>
                  取消
                </span>
              </>
            ) : (
              <>
                <span onClick={() => edit(record)} aria-hidden="true">
                  编辑
                </span>
                <Popconfirm
                  placement="topLeft"
                  title="你确定要删除这条数据吗？"
                  onConfirm={() => onDelete(record.key)}
                  okText="确定"
                  cancelText="取消"
                >
                  <span>删除</span>
                </Popconfirm>
              </>
            )}
          </div>
        ),
      });
    }
    return arr;
  }, [ladderColCount, pageType, editingKey, tabValue, offsetCount]);

  const mergedColumns = Colnums.map((col) => {
    if (!col.editable) {
      return col;
    }
    return {
      ...col,
      onCell: (record: any) => ({
        record,
        dataIndex: col.dataIndex,
        title: col.title,
        // eslint-disable-next-line no-shadow
        editing: record.key === editingKey,
      }),
    };
  });

  return (
    <div className={Styles.reward}>
      <Radio.Group
        value={tabValue}
        onChange={(e) => {
          setTabValue(e.target.value);
        }}
      >
        <Radio.Button value="1">阶梯奖励</Radio.Button>
        <Radio.Button value="2">冲单奖励</Radio.Button>
      </Radio.Group>

      {tabValue === '1' && (
        <div className={Styles.modeBox}>
          <span className={Styles.text}> 提档方式</span>
          <Radio.Group
            onChange={(v) => {
              setMode(v.target.value);
            }}
            value={mode}
          >
            <Radio value={1}>全部提档</Radio>
            <Radio value={2}>仅超出部分提档</Radio>
          </Radio.Group>
        </div>
      )}

      <div className={Styles.content}>
        {pageType !== PageType.Detail && (
          <div className={Styles.btnList}>
            <Button icon={<ArrowDownOutlined />} size="small">
              导出
            </Button>
            <Button type="primary" size="small" onClick={add}>
              新增
            </Button>
          </div>
        )}

        <Form form={form} component={false}>
          {tabValue === '1' ? (
            <Table
              components={{
                body: {
                  cell: EditableCell,
                },
              }}
              bordered
              scroll={{
                x: 2500,
              }}
              rowClassName="editable-row"
              columns={mergedColumns}
              dataSource={channelCodeList}
              pagination={{
                onChange: () => {
                  setEditingKey('');
                },
              }}
            />
          ) : (
            <Table
              components={{
                body: {
                  cell: EditableCell,
                },
              }}
              bordered
              scroll={{
                x: 2500,
              }}
              rowClassName="editable-row"
              columns={mergedColumns}
              dataSource={offsetList}
              pagination={{
                onChange: () => {
                  setEditingKey('');
                },
              }}
            />
          )}
        </Form>
      </div>
      <Modal
        width={1200}
        title="新增"
        open={visible}
        onCancel={() => setVisible(false)}
      >
        <Table
          rowKey="id"
          columns={RewardColumns}
          dataSource={rewardList}
          pagination={false}
          rowSelection={{
            type: 'checkbox',
            onChange: (ids, rows) => {
              setSelectRows(rows);
            },
          }}
        />
      </Modal>
    </div>
  );
}
